from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.contrib.auth.hashers import make_password, check_password
from django.core.urlresolvers import reverse
from .. import models
import time,os
from django.core.paginator import Paginator
from django.db.models import Q
from django.contrib.auth.decorators import permission_required


def tab():
    #查询拼接后的
    cates = models.Cates.objects.extra(select = {'newpath':'concat(paths,id)'}).order_by('newpath')
    for i in cates:
        num = i.paths.count(',')-1
        i.newname=num*'|----'
    return cates    
@permission_required('myadmin.create_User',raise_exception=True)
def addcate(request):
    if request.method=='GET':
        #讲所有的类型返回
        cates = tab()
        return render(request,'myadmin/cate/addcate.html',{'cates':cates})
    elif request.method =='POST':
        # 接受pid 通过pid来判断是不是顶级分类
        pid = request.POST.get('pid')
        name = request.POST.get('name')

        print(pid)
        print(name)
        if pid =='0':
            cate = models.Cates()
            cate.name = name
            cate.upid = int(pid)
            cate.paths='0,'
            cate.level = 1
            cate.save()
        else:
            #根据pid父级 paths
            pap = models.Cates.objects.get(id=pid)

            num = pap.paths.count(',') 

            thisc = models.Cates()
            thisc.name = name
            thisc.upid = pap.id
            thisc.paths = pap.paths+pid+','
            thisc.level =num+1
            thisc.save()
        # 接受数据添加数据
        return HttpResponse("<script>alert('添加成功！');location.href='/myadmin/catelist/'</script>")



    
@permission_required('myadmin.remove_Cates',raise_exception=True)
def catelist(request):
    cates = tab()



    #搜索功能
    #接受类型
    types = request.GET.get('type')
    #接受关键字
    search = request.GET.get('search')

    for i in cates:
        num = i.paths.count(',') 
    #判断是否搜索内容
        if types:
            if types=='all':
                cates = models.Cates.objects.filter(Q(name__contains=search))
            #查询
            elif types=='onelist':
                cates = models.Cates.objects.filter(Q(level__contains=1)&Q(name__contains=search))
            elif types == 'twolist':
                cates = models.Cates.objects.filter(Q(level__contains=2)&Q(name__contains=search))

            elif types=='threelist':
                cates = models.Cates.objects.filter(Q(level__gte=3)&Q(name__contains=search))



#     # 实例化分页对象
    p = Paginator(cates, 5)

    #一共可以分多少页
    sumpage=p.num_pages
# num_pages

    # 取第几页的数据
     # 接受用户的页码
    page = int(request.GET.get('p',1))
    # 第几页的数据
    page1 = p.page(page)

    # 判断 如果用输入的页码<=3 显示前五个页码
    if page<=3:
        # 页码的迭代序列  [1,2,3,4,5,6,7]
        prange = p.page_range[:5]
    elif page+2>=sumpage:
        prange = p.page_range[-5:]
    else:
        prange = p.page_range[page-3:page+2]
    return render(request,'myadmin/cate/catelist.html',{'cates':page1,'prange':prange,'page':page,'sumpage':sumpage})
    
@permission_required('myadmin.remove_Cates',raise_exception=True)
def delcate(request):
    #接收id
    pid = int(request.GET.get('pid'))
    #判断有没有子分类
    cnum = models.Cates.objects.filter(upid=pid).count()
    if cnum:
        return JsonResponse({'msg':0})
    else:
        c = models.Cates.objects.get(id = pid)
        c.delete()
        return JsonResponse({'msg':1})
@permission_required('myadmin.remove_Cates',raise_exception=True)
def editcate(request):
    # 接受id和name
    cid = int(request.GET.get('id'))
    cname = request.GET.get('name')
    try:
        cate = models.Cates.objects.get(id=cid)
        cate.name=cname
        cate.save()
        return JsonResponse({'msg':1})
    except :
        return JsonResponse({'msg':0})
